from fastapi import Request
from config.sms import EXPIRE
from saas.response.BaseResponse import success, fail
from saas.utils.utils import code_number
from extends.tencentcloud.SMS import send
from validator.service import PhoneCode


async def get_code(req: Request, data: PhoneCode):
    """
    发送验证码
    :param req: Request
    :param data: PhoneCode
    :return: dict
    """
    code = code_number(6)

    res = send(data.phone, data.web_code, code)
    if not res:
        return fail(msg='短信接口错误')
    res = res.SendStatusSet
    if res[0].Code != 'Ok':

        return fail(msg=res[0].Message)

    # 缓存手机号对应的验证码
    await req.app.state.code.set(key=data.web_code, value=code + '-' + data.phone, expire=EXPIRE)
    return success(msg='msg', data=res)


# 短信验证码校验
async def check_code(req: Request, verify_code: int, fast_code: str, phone: str):
    code = await req.app.state.code.get(key=fast_code)
    if not code:
        return False

    # 获取缓存中验证码
    if str(verify_code) + '-' + phone == code:
        return True
    else:
        return False
